package com.demo.youxuanmall.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/admin/users")
@RequiredArgsConstructor
public class AdminUserController {

    private final UserService userService;
    
    /**
     * 用户管理页面
     */
    @GetMapping
    public String usersPage(
            Model model,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return "redirect:/403";
        }
        
        // 校验分页参数合理性
        if (pageNum <= 0) {
            pageNum = 1;
        }
        
        if (pageSize <= 0 || pageSize > 50) {
            pageSize = 10;
        }
        
        try {
            // 查询用户统计
            Result<Integer[]> statsResult = userService.getUserStats();
            if (statsResult.getCode() == 0 && statsResult.getData() != null) {
                model.addAttribute("userStats", statsResult.getData());
            }
            
            // 根据是否有搜索关键词，执行不同的查询
            Result<Page<User>> result;
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 搜索用户
                result = userService.searchUsers(keyword, pageNum, pageSize);
            } else {
                // 查询所有用户
                result = userService.listAllUsers(pageNum, pageSize);
            }
            
            if (result.getCode() == 0 && result.getData() != null) {
                model.addAttribute("userPage", result.getData());
                model.addAttribute("keyword", keyword);
            } else {
                model.addAttribute("error", result.getMsg());
            }
            
            return "admin/user/list";
        } catch (Exception e) {
            log.error("加载用户管理页面出错", e);
            model.addAttribute("error", "加载失败，请稍后再试");
            return "admin/user/list";
        }
    }
    
    /**
     * AJAX异步加载用户列表
     */
    @GetMapping("/ajax")
    @ResponseBody
    public Result<Map<String, Object>> getUsersAjax(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "false") Boolean isReset,
            HttpSession session
    ) {
        log.info("AJAX请求用户列表: pageNum={}, pageSize={}, keyword={}, isReset={}", pageNum, pageSize, keyword, isReset);
        
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        // 校验分页参数合理性
        if (pageNum <= 0) {
            pageNum = 1;
        }
        
        if (pageSize <= 0 || pageSize > 50) {
            pageSize = 10;
        }
        
        try {
            // 查询用户统计
            Result<Integer[]> statsResult = userService.getUserStats();
            
            // 根据是否有搜索关键词，执行不同的查询
            Result<Page<User>> result;
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 搜索用户
                result = userService.searchUsers(keyword, pageNum, pageSize);
            } else {
                // 查询所有用户
                result = userService.listAllUsers(pageNum, pageSize);
            }
            
            // 组合用户数据和统计数据
            Map<String, Object> data = new HashMap<>();
            
            if (result.getCode() == 0 && result.getData() != null) {
                data.put("userPage", result.getData());
            }
            
            // 只有在全部用户查询或重置操作时才返回统计数据
            if (statsResult.getCode() == 0 && statsResult.getData() != null) {
                data.put("userStats", statsResult.getData());
                // 添加统计标记，表示此数据为全部用户的统计
                data.put("isFullStats", true);
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("异步加载用户列表出错", e);
            return Result.error("加载失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PostMapping("/status")
    @ResponseBody
    public Result<Void> updateStatus(
            @RequestParam Long userId,
            @RequestParam Integer status,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("更新用户状态: userId={}, status={}", userId, status);
            return userService.updateStatus(userId, status);
        } catch (Exception e) {
            log.error("更新用户状态异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户角色
     */
    @PostMapping("/role")
    @ResponseBody
    public Result<Void> updateRole(
            @RequestParam Long userId,
            @RequestParam Integer role,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("更新用户角色: userId={}, role={}", userId, role);
            return userService.updateRole(userId, role);
        } catch (Exception e) {
            log.error("更新用户角色异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result<Void> deleteUser(
            @RequestParam Long userId,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("删除用户: userId={}", userId);
            return userService.deleteUser(userId);
        } catch (Exception e) {
            log.error("删除用户异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 重置用户密码
     */
    @PostMapping("/reset-password")
    @ResponseBody
    public Result<Void> resetPassword(
            @RequestParam Long userId,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("重置用户密码: userId={}", userId);
            return userService.resetPassword(userId);
        } catch (Exception e) {
            log.error("重置用户密码异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
} 